/**
 * Sangame.com Inc.
 * Copyright (c) 2006-2011 All Rights Reserved.
 */
package com.nmp.service.weibo;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;

import com.nmp.config.CommonConfig;
import com.nmp.constant.EnumConstants.SiteType;
import com.nmp.persistence.dao.base.Page;
import com.nmp.persistence.dao.weibo.WeiboAccountDao;
import com.nmp.persistence.entity.WeiboAccount;
import com.nmp.service.base.result.DefaultResult;
import com.nmp.service.base.result.Result;
import com.nmp.service.base.result.ResultCode;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;

/**
 * 新浪微博接口
 * @author defier.lai
 * 2011-11-17 上午12:49:14
 * @version 1.0
 */
@Service
public class WeiboAccountService {
	
	private final static Logger LOG	= LoggerFactory.getLogger(WeiboAccountService.class);
	
	@Resource
	private CommonConfig commonConfig;
	@Resource
	private WeiboAccountDao weiboAccountDao;
	
	/**
	 * 绑定微博帐户，OAuth授权，新浪使用OAuth2.0, 腾讯使用OAuth1.0
	 */
	public Result getAccountAuthorizeUrl(int site) {
		Result result = new DefaultResult(true);
		try {
			if(site == SiteType.SINA.getValue()) { // 新浪微博
				Oauth oauth = new Oauth();
				String authorizeUrl = oauth.authorize("code");
				result.setModel("authorizeUrl", authorizeUrl);
				
			} else if(site == SiteType.TENCENT.getValue()) { // 腾讯微博
				OAuth oauth = new OAuth();
				oauth.setOauth_callback(commonConfig.getTencentCallback());
				OAuthClient auth = new OAuthClient();
				oauth = auth.requestToken(oauth);
				if (oauth.getStatus() != 0) {
					LOG.warn("Get Request Token failed! siteType:{}, status:{}", SiteType.TENCENT.getValue(), oauth.getStatus());
				} else {
					String oauth_token = oauth.getOauth_token();
					String authorizeUrl = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=" + oauth_token;
					result.setModel("authorizeUrl", authorizeUrl);
				}
			}
		} catch (Exception e) {
			LOG.error("authorize url is error!", e);
			result.setResultCode(new ResultCode(ResultCode.FAILURE));
		}
		return result;
	}

	/**
	 * 获取新浪微博access token,并与绑定帐户关联，持久化
	 * @param code
	 * @return
	 */
	public Result bindSinaWeiboToken(String code) {
		Result result = new DefaultResult(true);
		try {
			Oauth oauth = new Oauth();
			AccessToken accessToken = oauth.getAccessTokenByCode(code);
			if(LOG.isDebugEnabled()) {
				LOG.debug("sina weibo code:{}, accessToken: {}", code, accessToken.getAccessToken());
			}
			Weibo weibo = new Weibo();
	        weibo.setToken(accessToken.getAccessToken());
	        Account account = new Account();
	        String uid = account.getUid().getString("uid");
	         //	TODO 把绑定的uid与token绑定在一起
	        System.out.println(uid);
	         
		} catch (Exception e) {
			LOG.error("sina weibo user callback is error!", e);
			result.setResultCode(new ResultCode(ResultCode.FAILURE));
		}
		return result;
	}

	/**
	 * 获取腾讯微博access token,并与绑定帐户关联，持久化
	 * @param code
	 * @return
	 */
	public Result bindTencentWeiboToken(String oauthToken, String verifier) {
		Result result = new DefaultResult(true);
		try {
			OAuth oauth = new OAuth();
			OAuthClient auth = new OAuthClient();
			oauth.setOauth_token(oauthToken);
			oauth.setOauth_verifier(verifier);
	        oauth = auth.accessToken(oauth);
	        System.out.println(oauth.getOauth_token());
	         
		} catch (Exception e) {
			LOG.error("tencent weibo user callback is error!", e);
			result.setResultCode(new ResultCode(ResultCode.FAILURE));
		}
		return result;
	}

	/**
	 * 根据站点类型查询微博帐户
	 * @param siteType
	 * @return
	 */
	public Result findWeiboAccountBySiteType(int siteType, int pageSize, int currentPage) {
		Result result = new DefaultResult(true);
		try {
			Page<WeiboAccount> page = weiboAccountDao.findPage(siteType, pageSize, currentPage);
			result.setDefaultModel(page);
			
		} catch (Exception e) {
			LOG.error("find weibo account is error!", e);
			result.setResultCode(new ResultCode(ResultCode.FAILURE));
		}
		return result;
	}
	

}
